<?php
namespace app\index\controller;

use app\Basic;
use EasyWeChat\Kernel\Exceptions\HttpException;
use Flc\Dysms\Client;
use Flc\Dysms\Request\SendSms;
use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\DecodingExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
use \think\facade\Db;
use think\facade\Config;

class Login extends Basic
{
    public function tel_login()
    {
        $tel = (string)input('param.tel');
        $code = (string)input('param.code');
        $code_info = Db::name('code')->where([
            ['tel', '=', $tel],
            ['type', '=', 'login_code'],
            ['code', '=', $code],
            ['add_time', '>', time() - 60 * 20],
        ])->find();
        if (!$code_info) {
            return $this->ajax_return(0, '验证码不正确', []);
        }
        $user_info = DB::name('user')->where([
            ['tel', '=', $tel],
        ])->find();

        if ($user_info) {
            $user_id = $user_info['user_id'];
        } else {
            $user_id = DB::name('user')->insertGetId([
                'tel' => $tel,
                'password' => '123456',
                'add_time' => time(),
            ]);
            $user_info = DB::name('user')->where([
                ['tel', '=', $tel],
            ])->find();
        }
        $token = md5(uniqid() . $user_id);
        Db::name('token')->insert([
            'token' => $token,
            'token_user_id' => $user_info['user_id'],
            'ip' => $this->request->ip(),
            'add_time' => time(),
        ]);
        Db::name('user_log')->insert([
            'name' => $user_info['username'],
            'user_id' => $user_info['user_id'],
            'url' => $this->request->url(),
            'ip' => $this->request->ip(),
            'add_time' => time(),
            'title' => '手机号登录',
        ]);
        return $this->ajax_return(1, '登录成功', [
            'user_id' => $user_id,
            'token' => $token,
        ]);
    }
    public function code_to_openid(){
        $config = [
            'app_id' => Config::get('app.xcx_app_id'),
            'secret' => Config::get('app.xcx_secret'),
        ];
        $app = new \EasyWeChat\MiniApp\Application($config);
        $utils = $app->getUtils();
        $response=null;

        try {
            $response = $utils->codeToSession($this->param['code']);
        } catch (\Exception $e) {
            return $this->error('解析失败1',[
                '$response'=>$response,
                '$e'=>$e->getMessage(),
            ]);
        }

        if(empty($response['openid'])){
            return $this->error('解析失败2',[
                '$response'=>$response,
            ]);
        }
        $openid = $response['openid'];

        $user_info = DB::name('user')->where([
            ['openid', '=', $openid],
        ])->find();

        if ($user_info) {
            $user_id = $user_info['user_id'];
        } else {
            $user_id = DB::name('user')->insertGetId([
                'openid' => $openid,
                'password' => '123456',
                'username' => '',
                'add_time' => time(),
            ]);
            $user_info = DB::name('user')->where([
                ['openid', '=', $openid],
            ])->find();
        }
        $token = md5(uniqid() . $user_id);
        $has_token = Db::name('token')->where('token_user_id', $user_id)->find();
        if ($has_token) {
            Db::name('token')->where('token_id', $has_token['token_id'])->update([
                'token' => $token,
                'token_user_id' => $user_id,
                'ip' => $this->request->ip(),
                'add_time' => time(),
            ]);
        } else {
            Db::name('token')->insert([
                'token' => $token,
                'token_user_id' => $user_id,
                'ip' => $this->request->ip(),
                'add_time' => time(),
            ]);
        }

        Db::name('user_log')->insert([
            'name' => $user_info['username'],
            'user_id' => $user_info['user_id'],
            'url' => $this->request->url(),
            'ip' => $this->request->ip(),
            'add_time' => time(),
            'title' => '微信静默登录',
        ]);

        return $this->ajax_return(1, '登录成功', [
            'user_id' => $user_id,
            'openid'=>$response['openid'],
            'token' => $token,
        ]);
    }
    public function douyin_code_to_openid(){
        $client = new \GuzzleHttp\Client(['verify' => false ]);
        $res = $client->request('POST', "https://developer.toutiao.com/api/apps/v2/jscode2session",[
            'headers'=>[
                'Content-Type'=>'application/json',
            ],
            'body'=>json_encode([
                'appid'=>Config::get('app.douyin_xcx_app_id'),
                'secret'=>Config::get('app.douyin_xcx_secret'),
                'code'=>$this->param['code'],
            ])
        ]);
        $response=$res->getBody()->getContents();
        if(empty($response)){
            return $this->ajax_return(0,'获取token失败',[
                '$response'=>$response,
            ]);
        }
        $response=json_decode($response,true);
        if(empty($response['data']['openid'])){
            return $this->error('解析失败2',[
                '$response'=>$response,
            ]);
        }
        $openid = $response['data']['openid'];
        $user_info = DB::name('user')->where([
            ['openid', '=', $openid],
        ])->find();
        if ($user_info) {
            $user_id = $user_info['user_id'];
        } else {
            $user_id = DB::name('user')->insertGetId([
                'nickname' => substr($openid,4,6),
                'openid' => $openid,
                'password' => '123456',
                'username' => '',
                'add_time' => time(),
            ]);
            $user_info = DB::name('user')->where([
                ['openid', '=', $openid],
            ])->find();
        }
        $token = md5(uniqid() . $user_id);

        Db::name('token')->insert([
            'token' => $token,
            'token_user_id' => $user_id,
            'ip' => $this->request->ip(),
            'add_time' => time(),
        ]);

        Db::name('user_log')->insert([
            'name' => $user_info['nickname']?$user_info['nickname']:$user_info['username'],
            'user_id' => $user_info['user_id'],
            'url' => $this->request->url(),
            'ip' => $this->request->ip(),
            'add_time' => time(),
            'title' => '抖音静默登录',
        ]);

        return $this->success( '登录成功', [
            'user_id' => $user_id,
            'openid'=>$openid,
            'token' => $token,
        ]);
    }
    public function xcx_login(){
        $config = [
            'app_id' => Config::get('xcx_app_id'),
            'secret' => Config::get('xcx_app_secret'),
        ];
        $latitude = (string)input('param.latitude');
        $longitude = (string)input('param.longitude');
        $share_id = (int)input('param.share_id',0); // 分享的user_id
        $user_country=$user_province=$user_city=$user_district=$formatted_address='';
        $app = new \EasyWeChat\MiniApp\Application($config);
        $utils = $app->getUtils();

        $session = $utils->codeToSession($this->param['code']);
        if(empty($session['session_key'])){
            return $this->error('参数不正确2',['$session'=>$session]);
        }
        $decryptedData = $utils->decryptSession($session['session_key'], $this->param['iv'], $this->param['encryptedData']);

        $openid = $session['openid'];
        $wxData = $app->encryptor->decryptData($session['session_key'], $iv, $encryptedData);
        if(!$wxData||!isset($wxData['nickName'])){
            $this->ajax_return(0,'解析不正确',['$wxData'=>$wxData,'$session'=>$session]);
        }

        $geohash='';
        if($latitude&&$longitude){
            $amap_options = [
                'sign'=>false, //是否进行数字签名，默认不签名
                'private_key'=>'', //数字签名私钥，sign=true时必填
                'key'=>Config::get('amap_key')//api调用key，必填
            ];
            $map = new Amap($amap_options);
            $locationData = $map->regeo($longitude.','.$latitude);
//            return $this->ajax_return(1,'登录成功2',['user_info'=>$locationData]);
            $user_country = isset($locationData['regeocode']['addressComponent']['country'])&&$locationData['regeocode']['addressComponent']['country']?$locationData['regeocode']['addressComponent']['country']:'';
            $user_province = isset($locationData['regeocode']['addressComponent']['province'])&&$locationData['regeocode']['addressComponent']['province']?$locationData['regeocode']['addressComponent']['province']:'';
            $user_city     = isset($locationData['regeocode']['addressComponent']['city'])&&$locationData['regeocode']['addressComponent']['city']?$locationData['regeocode']['addressComponent']['city']:$user_province;
            $user_district = isset($locationData['regeocode']['addressComponent']['district'])&&$locationData['regeocode']['addressComponent']['district']?$locationData['regeocode']['addressComponent']['district']:'';
            $formatted_address = isset($locationData['regeocode']['formatted_address'])&&$locationData['regeocode']['formatted_address']?$locationData['regeocode']['formatted_address']:'';
            $geohash= GeoHash::encode($longitude,$latitude);
        }

        $user_info = Db::name('users')->where('openid',$openid)->find();
        if(!$user_info){
            Db::name('users')->insert([
                'avatar'  => $wxData['avatarUrl'],
                'country' => $user_country ?$user_country :$wxData['country'],
                'province'=> $user_province?$user_province:$wxData['province'],
                'city'    => $user_city    ?$user_city    :$wxData['city'],
                'district'=> $user_district?$user_district:'',
                'nickname' =>filter_Emoji($wxData['nickName']),
                'openid' => $openid,
                'share_id' => $share_id,
                'formatted_address' => $formatted_address,
                'latitude' => $latitude,
                'longitude' => $longitude,
                'geohash' => $geohash,
                'add_time' => time(),
            ]);
        }else{
            Db::name('users')->where('openid',$openid)->update([
                'avatar'  => $wxData['avatarUrl'],
                'country' => $user_country ?$user_country :$wxData['country'],
                'province'=> $user_province?$user_province:$wxData['province'],
                'city'    => $user_city    ?$user_city    :$wxData['city'],
                'district'=> $user_district?$user_district:'',
                'nickname' =>filter_Emoji($wxData['nickName']),
                'openid' => $openid,
                'formatted_address' => $formatted_address,
                'latitude' => $latitude,
                'longitude' => $longitude,
                'geohash' => $geohash,
                'update_time' => time(),
            ]);
        }
        $user_info = Db::name('users')->where('openid',$openid)->find();
        $user_info['clerk']=Db::name('clerk')->where('user_id',$user_info['user_id'])->find();
        return $this->ajax_return(1,'登录成功',['user_info'=>$user_info]);
    }
}
